/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.registration.business.security.boundary;

import it.polimi.registration.business.security.entity.Calendar;
import it.polimi.registration.business.security.entity.Group;
import it.polimi.registration.business.security.entity.User;

import java.security.Principal;
import java.util.List;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author miglie
 */
@Stateless
public class UserManager {

    @PersistenceContext
    EntityManager em;
    
    @Inject
    Principal principal;

    @Inject
    private Logger logger;
    
    @EJB
    CalendarManager cm;

    public void save(User user) {
        user.setGroupName(Group.USERS);
        
        Calendar c = new Calendar(user);
        user.setCalendar(c);
        
        cm.save(c);
        em.persist(user);
    }
    
    public void merge(User u) {
		em.merge(u);
    }

    public void unregister() {
        em.remove(getLoggedUser());
    }

    public User getLoggedUser() {
    	//logger.log(Level.SEVERE,"Get logged user : " + principal.getName());
    	return (User) em.createQuery("SELECT t FROM user t where t.emailAddress = :value1")
                .setParameter("value1", principal.getName()).getSingleResult();
    }

	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {
		return em.createQuery("SELECT t FROM user t where t.emailAddress != :value1").setParameter("value1", principal.getName()).getResultList();
	}

	public User get(int id) {
		return (User) em.createQuery("SELECT t FROM user t where t.id = :value1")
                .setParameter("value1", id).getSingleResult();
	}
    
}
